const fs = require('fs')
const parseXlsx = require('excel').default
const Axios = require('axios')
const TimeAgo = require('javascript-time-ago')
require('javascript-time-ago/load-all-locales')
const timeAgo = new TimeAgo('zh')

// 可选 gitee 的 access_token，避免过多调用屏蔽问题
// 请参考 getToken.js 和 gitee api 文档
// 设为 false 则不验证
// const giteeToken = 'fca92b53c25e24750e47f5bfd384541d'
const giteeToken = false

// 数据源
const excelFilePath = '广州57 前端项目 git 地址.xlsx'
// 姓名列
const nameColIndex = 1
// 地址列
const urlColIndex = 2
// 表头跳过行数
const numLineToShift = 2
// 结果文件路径
const file = './homework.md'

// 初始化 markdown 表头
initMdFile()
// 处理 excel 文件
parseExcel();


function initMdFile() {
    let init = `|姓名|时间|注释|仓库|\n|---|---|---|---|\n`
    fs.writeFileSync(file, init);
}

function parseExcel() {
    parseXlsx(excelFilePath).then(async (data) => {

        const githubExp = /^.*github.com\/(.+)\/?$/
        const giteeExp = /^.*gitee.com\/(.+)\/?$/
        let promisArr = []
        let missionComplete = 0

        // 清理表头和无姓名数据
        data = removeUselessData(data)

        // 处理有链接的行
        for(let index = 0; index < data.length; index++) {
            await sleep(800)
            const element = data[index];
            const urlRepo = element[urlColIndex].replace(/\.git$/, '')
            const name = element[nameColIndex]
            let params = {
                per_page: 1
            }

            let urlApi = ''
            if(urlRepo.indexOf('github') > 0) {
                const resExp = githubExp.exec(urlRepo)
                urlApi = `https://api.github.com/repos/${resExp[1]}/commits`
            }

            if(urlRepo && urlRepo.indexOf('http') >= 0 && urlRepo.indexOf('github') < 0) {
                const resExp = giteeExp.exec(urlRepo)
                urlApi = `https://gitee.com/api/v5/repos/${resExp[1]}/commits`
                if(giteeToken) {
                    params.access_token = giteeToken
                }
            }

            if(urlApi) {
                const request = Axios({
                    url: urlApi,
                    params
                }).then(res => {
                    const commit = res.data[0].commit
                    const date = formatDate(commit.committer.date)

                    let str = `|${name}|${date}|`

                    str += commit.message.replace('\n', '') + "|"

                    str += `[仓库地址](${urlRepo})|`;

                    str += '\n';

                    fs.writeFileSync(file, str, {
                        flag: 'a'
                    });

                    console.log(((++missionComplete / data.length) * 100).toFixed(2) + "%");

                }).catch(err => {
                    let errMsg = "未知错误"
                    if(err.response) {
                        errMsg = err.response.data.message || err.response.data
                    }
                    const str = `|${name}|失败,请手动获取|${errMsg}|[仓库地址](${urlRepo})|\n`
                    fs.writeFileSync(file, str, {
                        flag: 'a'
                    });
                })

                // 添加到数组准备用来监听完成状态
                promisArr.push(request)
            }

        }
        Promise.all(promisArr).then(res => {
            console.log("完成...");
        })
    });
}

function removeUselessData(data) {
    // 清理无用数据
    for(let index = 0; index < numLineToShift; index++) {
        data.shift()
    }

    return data.filter(element => {
        return element[nameColIndex] && element[urlColIndex]
    })
}

function formatDate(dateStr) {
    let date = new Date(dateStr);
    return timeAgo.format(date) + date.getHours() + ":" + date.getMinutes()
}

function sleep(time) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, time);
    })
}